package br.com.ordersys.web.jobs;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.ordersys.framework.db.DBSessionManager;
import br.com.ordersys.framework.db.IDBSession;
import br.com.ordersys.framework.db.IValueObject;
import br.com.ordersys.framework.scheduler.IScheduledJob;
import br.com.ordersys.framework.scheduler.JobInfo;
import br.com.ordersys.framework.scheduler.JobRunningContext;
import br.com.ordersys.framework.scheduler.JobTrigger;
import br.com.ordersys.framework.scheduler.JobTrigger.Type;

@Service("job.test")
@JobInfo(description = "Job Teste", id = "job.teste", type = Type.INTERVAL_TYPE, interval = 3)
public class JobTestImpl implements IScheduledJob {

	@Override
	@Transactional
	public void doWork(JobRunningContext jrc) {
		IDBSession dbSession = null;
		try {
			dbSession = DBSessionManager.open();
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

			Date now = new Date();
			
			IValueObject vo = dbSession.findByPK("Usuario", 1);
			System.out.println("JobTestImpl.doWork: " + vo.asString("EMAIL") + ", " + sdf.format(now));
			
			Calendar c = new GregorianCalendar();
			c.add(Calendar.SECOND, 10);
			
			JobTrigger jt = JobTrigger.buildExecuteOnceTrigger(c.getTime());
			jrc.redefineScheduling(jt);
		} finally {
			DBSessionManager.close(dbSession);
		}
	}

}
